<?php

/**
 * Created by PhpStorm.
 * User: lixy
 * Date: 2016/4/18
 * Time: 17:20
 */

class SmsSdk
{
    private $account = '账户';
    private $token = 'token';

    public $baseurl = 'http://xxxx/sms/';

    function __construct($account='',$token='',$baseurl='')
    {
        if($baseurl!=''){
            $this->baseurl=$baseurl;
        }
        if($token!=''){
            $this->token=$token;
        }
        if($account!=''){
            $this->account=$account;
        }
    }

    function sendSms($template_id,$to,$data)
    {


        $timestamp = time();

        $sign = hash_hmac('sha256', $this->account . $this->token . $timestamp, $this->token);
        $url = $this->baseurl.'/send-template-sms' . "?account={$this->account}&timestamp={$timestamp}&sign={$sign}";



        if(is_array($data)==false) {
            $data = explode(',', $data);
        }

        $result = static::postJson($url, [
            'to' => $to,
            'data' => $data,
            'template_id' => $template_id,

        ], true);
        return json_decode($result);
    }

    function sendVoiceVerify($to,$data)
    {


        $timestamp = time();

        $sign = hash_hmac('sha256', $this->account . $this->token . $timestamp, $this->token);
        $url = $this->baseurl.'/send-voice-verify' . "?account={$this->account}&timestamp={$timestamp}&sign={$sign}";

        $result = static::postJson($url, [
            'to' => $to,
            'data' => $data,

        ], true);
        return json_decode($result);
    }

    static  function postJson($url,$data,$JSON_UNESCAPED_UNICODE=false){
        // $data = array("name" => "Hagrid", "age" => "36");
        if($JSON_UNESCAPED_UNICODE) {
            $data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
        }else{
            $data_string = json_encode($data);
        }
        $ch = curl_init($url);
        //https 请求
        if ( strlen( $url ) > 5 && strtolower( substr( $url , 0 , 5 ) ) == 'https' ){
            curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , FALSE );
            curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , FALSE );
        }

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string),
                'charset=utf-8',)

        );

        $result = curl_exec($ch);
        return $result;
    }

}